package com.fanrenqiji.modules.sys.web;

import com.fanrenqiji.common.config.GlobalSetting;
import com.fanrenqiji.common.persistence.Page;
import com.fanrenqiji.common.security.Digests;
import com.fanrenqiji.common.utils.StringUtils;
import com.fanrenqiji.common.utils.SystemAuthorizingCacheUtils;
import com.fanrenqiji.common.web.BaseController;
import com.fanrenqiji.modules.sys.entity.Office;
import com.fanrenqiji.modules.sys.entity.Role;
import com.fanrenqiji.modules.sys.entity.User;
import com.fanrenqiji.modules.sys.service.OfficeService;
import com.fanrenqiji.modules.sys.service.SystemService;
import com.fanrenqiji.modules.sys.service.UserService;
import com.fanrenqiji.modules.sys.utils.UserUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**                                                         
 * @author lijian E-mail:ljz0721cx@163.com
 * @version 创建时间：2015年1月16日 上午11:10:21
 * @description 用户
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/user")
public class UserController extends BaseController {

	@Autowired
	private SystemService systemService;
	@Autowired
	private UserService userService;
	@Autowired
	private OfficeService officeService;

	/**
	 * 为用户数据视图绑定Model
	 * 
	 * @param id
	 * @return
	 */
	@ModelAttribute
	public User get(@RequestParam(required = false) Long id) {
		if (id != null) {
			return systemService.getUser(id);
		} else {
			return new User();
		}
	}

	/**
	 * 获得用户的分页列表
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = { "list", "" })
	@RequiresPermissions(value = "sys:user:view")
	public String list(User user, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Page<User> userPage = systemService.findUserByPage(new Page<User>(
				request, response), user);
		model.addAttribute("page", userPage);
		model.addAttribute("currentUser", UserUtils.getUser());
		return "modules/sys/userList";
	}

	/**
	 * 用户更新页面
	 * 
	 * @param model
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "form")
	@RequiresPermissions(value = "sys:user:view")
	public String form(Model model, User user) {
		// 获得用户的所在公司机构
		if (user.getCompany() == null || user.getCompany().getId() == null) {
			user.setCompany(UserUtils.getUser().getCompany());
		}
		// 用户所在的公司部门
		if (user.getOffice() == null || user.getOffice().getId() == null) {
			user.setOffice(UserUtils.getUser().getOffice());
		}
		model.addAttribute("user", user);
		model.addAttribute("allRoles", user.getRoleList());

		// 可分配角色

		model.addAttribute("currentUser", UserUtils.getUser());
		return "modules/sys/userModify";
	}

	/**
	 * 用户添加页面
	 * 
	 * @param model
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "add")
	@RequiresPermissions(value = "sys:user:view")
	public String add(Model model, User user) {
		// 获得用户的所在公司机构
		if (user.getCompany() == null || user.getCompany().getId() == null) {
			user.setCompany(UserUtils.getUser().getCompany());
		}
		// 用户所在的公司部门
		if (user.getOffice() == null || user.getOffice().getId() == null) {
			user.setOffice(UserUtils.getUser().getOffice());
		}
		model.addAttribute("user", user);
		model.addAttribute("allRoles", systemService.findAllRole());
		return "modules/sys/userForm";
	}

	/**
	 * 修改用户
	 * 
	 * @param user
	 * @param oldLoginName
	 *            原来的密码
	 * @param newPassword
	 * @param request
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions(value = "sys:user:edit")
	@RequestMapping(value = "modify")
	public String modify(@ModelAttribute("user") User user,
			String oldLoginName, String newPassword,
			HttpServletRequest request, Model model,
			RedirectAttributes redirectAttributes) {
		// 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
		userService.combineUser(user, request);
		// 如果新密码为空，则不更换密码
		if (StringUtils.isNotBlank(newPassword)) {
			user.setPassword(Digests.entryptPassword(newPassword));
		}
		if (!beanValidator(model, user)) {
			model.addAttribute("user", user);
			model.addAttribute("allRoles", systemService.findAllRole());
			return "modules/sys/userModify";
		}
		// 判断用户名在和原来相同的时候通过，如果不同提示不能修改登陆名
		if (!"true".equals(checkLoginName(oldLoginName, user.getLoginName()))) {
			addMessage(redirectAttributes, "保存用户'" + oldLoginName
					+ "'失败，登录名已经存在！");
			return "redirect:" + GlobalSetting.getAdminPath()
					+ "/sys/user/form?id=" + user.getId();
		}
		// 角色数据有效性验证，过滤不在授权内的角色
		List<Role> roleList = Lists.newArrayList();
		List<Long> roleIdList = user.getRoleIdList();
		for (Role r : systemService.findAllRole()) {
			if (roleIdList.contains(r.getId())) {
				roleList.add(r);
			}
		}
		user.setRoleList(roleList);
		// 保存用户信息
		systemService.saveUser(user);
		// 清除当前用户缓存
		if (user.getLoginName().equals(UserUtils.getUser().getLoginName())) {
			SystemAuthorizingCacheUtils.getCacheMap().clear();
		}
		addMessage(redirectAttributes, "保存用户'" + user.getLoginName() + "'成功");
		return "redirect:" + GlobalSetting.getAdminPath() + "/sys/user/?repage";
	}

	/**
	 * 添加用户
	 * 
	 * @param user
	 * @param oldLoginName
	 *            原来的密码
	 * @param newPassword
	 * @param request
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions(value = "sys:user:edit")
	@RequestMapping(value = "save")
	public String save(@ModelAttribute("user") User user, String oldLoginName,
			String newPassword, HttpServletRequest request, Model model,
			RedirectAttributes redirectAttributes) {
		// 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
		/*
		 * user.setCompany(new
		 * Office(StringUtils.toLong(request.getParameter("company.id"))));
		 * user.setOffice(new
		 * Office(StringUtils.toLong(request.getParameter("office.id"))));
		 */
		if (null != systemService.findByLoginName(user.getLoginName())) {
			addMessage(redirectAttributes, "保存用户失败:该用户已经存在！");
			return "redirect:" + GlobalSetting.getAdminPath()
					+ "/sys/user/?repage";
		}
		userService.combineUser(user, request);
		// 如果新密码为空，则不更换密码
		if (StringUtils.isNotBlank(newPassword)) {
			user.setPassword(Digests.entryptPassword(newPassword));
		}
		if (!beanValidator(model, user)) {
			model.addAttribute("user", user);
			model.addAttribute("allRoles", systemService.findAllRole());
			return "modules/sys/userForm";
		}

		// 判断用户名在和原来相同的时候通过，如果不同提示不能修改登陆名
		if (!"true".equals(checkLoginName(oldLoginName, user.getLoginName()))) {
			addMessage(redirectAttributes, "保存用户'" + oldLoginName
					+ "'失败，登录名已经存在！");
			return "redirect:" + GlobalSetting.getAdminPath()
					+ "/sys/user/add?id=" + user.getId();
		}

		// 角色数据有效性验证，过滤不在授权内的角色
		List<Role> roleList = Lists.newArrayList();
		List<Long> roleIdList = user.getRoleIdList();

		// 如果用户所在组织机构级别为2级，3级，4级
		if (("3,4,5").contains(user.getOffice().getGrade())) {
			Long counts = systemService.findOfficeBelowIsExistUser(user
					.getOffice().getId());
			// 不存在用户则默认将添加的该用户赋予公司负责人角色
			if (counts == 0) {
				// 如果用户没有在页面选择公司负责人角色，系统自动添加
				if (!roleIdList.contains(new Long(9))) {
					roleIdList.add(new Long(9));
				}
			} else {
				// 如果用户在页面选择公司负责人角色，系统自动过滤掉
				if (roleIdList.contains(new Long(9))) {
					roleIdList.remove(new Long(9));
				}
			}
		}
		for (Role r : systemService.findAllRole()) {
			if (roleIdList.contains(r.getId())) {
				roleList.add(r);
			}
		}
		user.setRoleList(roleList);
		// 保存用户信息
		systemService.saveUser(user);
		// 清除当前用户缓存
		if (user.getLoginName().equals(UserUtils.getUser().getLoginName())) {
			SystemAuthorizingCacheUtils.getCacheMap().clear();
		}
		addMessage(redirectAttributes, "保存用户'" + user.getLoginName() + "'成功");
		return "redirect:" + GlobalSetting.getAdminPath() + "/sys/user/?repage";
	}

	/**
	 * 校验用户登陆名是否已经存在
	 * 
	 * @param oldLoginName
	 * @param loginName
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "checkLoginName")
	public String checkLoginName(String oldLoginName, String loginName) {
		if (loginName != null && loginName.equals(oldLoginName)) {
			return "true";
		} else if (loginName != null
				&& systemService.findByLoginName(loginName) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 获得当前登陆的用户
	 * 
	 * @param user
	 * @param model
	 * @return
	 */
	@RequiresUser
	@RequestMapping(value = "info")
	public String info(User user, Model model) {
		User currentUser = UserUtils.getUser();
		model.addAttribute("user", currentUser);
		return "modules/sys/userInfo";
	}

	/**
	 * 修改当前登陆用户的密码
	 * 
	 * @param oldPassword
	 * @param newPassword
	 * @param model
	 * @return
	 */
	@RequiresUser
	@RequestMapping(value = "modifyPwd")
	public String modifyPwd(String oldPassword, String newPassword, Model model) {
		User user = UserUtils.getUser();
		// 如果新旧密码为空只展示修改密码框
		if (StringUtils.isNotBlank(oldPassword)
				&& StringUtils.isNotBlank(newPassword)) {
			if (Digests.validatePassword(oldPassword, user.getPassword())) {
				systemService.updatePasswordById(user.getId(),
						user.getLoginName(), newPassword);
				model.addAttribute("message", "修改密码成功");
				// SecurityUtils.getSubject().logout();
			} else {
				model.addAttribute("message", "修改密码失败，旧密码错误");
			}
		}
		model.addAttribute("user", user);
		return "modules/sys/userModifyPwd";
	}

	/**
	 * 获得机构树
	 * 
	 * @param extId
	 * @param type
	 * @param grade
	 * @param response
	 * @return
	 */
	@RequiresUser
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(
			@RequestParam(required = false) Long extId,
			@RequestParam(required = false) Long type,
			@RequestParam(required = false) Long grade,
			HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		Office office = officeService.findById(2l);
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<User> list = systemService.findUserByOffice(office);
		for (int i = 0; i < list.size(); i++) {
			User e = list.get(i);
			if (!e.getRoleIdList().contains(16l)) {
				continue;
			}
			if (extId == null || (extId != null && !extId.equals(e.getId()))) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", 0);
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}

	/*
	 * public static void main(String[] args) { if(("3,4,5").contains("3")){
	 * System.out.println("33333333333333333");
	 * 
	 * } }
	 */
}
